const {con} = require('../db/db');

async function getUserList(page) {
    const sql = `select * from user order by id limit ${(page-1)*10},10;`;

    const total = `select * from user;`;

    let [rows] = await con.execute(sql);

    let [totals] = await con.execute(total);

    return {data:rows,total:totals.length}
}

async function getMineInfo(id) {
    const sql = `select username,avatar from user where id=${id};`;

    let [rows] = await con.execute(sql);

    return rows[0];
}

async function getMyFollow(userid,followid) {
    const sql = `select * from user_collect where userid=${userid} and followid=${followid};`

    let [rows] = await con.execute(sql);

    if(rows.length > 0) {
        return {code:200}
    }else{
        return {code:500}
    }
}

async function addFollow(followid,userid,state) {
    if(state === false) {
        const sql_update = `update user set follows=follows+1 where id=${followid};`;
        await con.execute(sql_update);
        const sql_insert = `insert into user_collect(followid,userid,create_time) values(${followid},${userid},"${new Date().toLocaleString()}");`;
        await con.execute(sql_insert);

        return {code:200,state:'followed'};
    }else{
        const sql_update = `update user set follows=follows-1 where id=${followid};`;
        await con.execute(sql_update);
        const sql_delete = `delete from user_collect where followid=${followid} and userid=${userid};`;
        await con.execute(sql_delete);

        return {code:200,state:'unfollowed'};
    }
}

async function changeName(username,userid) {
    const sql_update = `update user set username='${username}' where id=${userid};`;

    await con.execute(sql_update);

    const sql_select = `select * from user where id=${userid};`;

    let [rows] = await con.execute(sql_select);

    return {code:200,data:rows[0]}
}

module.exports={
    getUserList,
    getMineInfo,
    getMyFollow,
    addFollow,
    changeName
}